#include "Object.h"

Object::Object(float x, float y, float z, float width, float height, KEY_TYPE key, ALIGNMENT horizalign, ALIGNMENT vertalign) 
: OrthoObject(x,y,z)
, dimensions(width, height)
, myKey(key)
, horizAlignment(horizalign)
, vertAlignment(vertalign)
, padding(0)
{
	//Default to NOT being drawn
	DisableDraw();
}

bool Object::operator<(const Object& o) {
	return drawPos.z < o.drawPos.z;	//Want to be in z-ordering
}

bool ObjectPointerLessThan::operator()(Object* a, Object* b) const {
	if(a == NULL || b == NULL)	return true;
// Test which direction the less than should go, if they're equal then just test the pointers for a defined order
	bool A = *a < *b;
	if(A == (*b < *a))
		return a < b;
	return A;
}

ObjectKeyEqual::ObjectKeyEqual(KEY_TYPE b): key(b) {}
bool ObjectKeyEqual::operator()(const Object* o) {
	if(o == NULL)	return false;
	return o->myKey == key;		//simple test
}

ObjectClickHit::ObjectClickHit(float x, float y): x(x), y(y) {}
bool ObjectClickHit::operator()(const Object* o) {
	if(o == NULL) return false;
	// Standard point in aligned rectangle collision test
	return (x >= o->drawPos.x && x <= o->drawPos.x+o->dimensions.x &&
		   y >= o->drawPos.y && y <= o->drawPos.y+o->dimensions.y);
}

void Object::loadFromXML(ticpp::Node* node, int Z, Frame*) {
	drawPos.z = Z;
	
	using namespace ticpp;	
	Element* elem = node->ToElement();
	
// Load all values, never throw an exception if an attribute is missing
	elem->GetAttribute("x", &drawPos.x, false);
	elem->GetAttribute("y", &drawPos.y, false);
	elem->GetAttribute("z", &drawPos.z, false);
	elem->GetAttribute("r", &color.r, false);
	elem->GetAttribute("g", &color.g, false);
	elem->GetAttribute("b", &color.b, false);
	elem->GetAttribute("width", &dimensions.x, false);
	elem->GetAttribute("height", &dimensions.y, false);
	elem->GetAttribute("padding", &padding, false);
	std::string val;
	elem->GetAttribute("key", &val, false);
	myKey = getKey(val);
	elem->GetAttribute("horizAlignment", &val, false);
	getAlignment(horizAlignment, val, true);
	val = "";
	elem->GetAttribute("vertAlignment", &val, false);
	getAlignment(vertAlignment, val, false);
}

void Object::enable() {
	EnableDraw();
}

void Object::disable() {
	DisableDraw();
}

void getAlignment(ALIGNMENT& a, const std::string &str, bool horiz) {
	if(str == "")
		return;
	if(horiz) {
		if(str == "left")			a = LEFT;
		else if(str == "right")		a = RIGHT;
		else if(str == "middle")		a = HORIZ_MIDDLE;
		else						a = ABSOLUTE;
	} else {
		if(str == "top")			a = TOP;
		else if(str == "bottom")		a = BOTTOM;
		else if(str == "middle")		a = VERT_MIDDLE;
		else						a = ABSOLUTE;
	}
}

